﻿using System;
using System.Linq;
using System.Threading.Tasks;
using HengTong.Model.Db;
using HengTong.Model.Db.Hr;
using HengTong.Model.Db.Hr.Bill;
using Microsoft.EntityFrameworkCore;
using TiaoTaoHelper.Models;
using TiaoTaoHelper.Wtm.Models;

namespace HengTong.ViewModel.Hr.SysHrRecruitPublishRequestBillVms;

public partial class SysHrRecruitPublishRequestBillBatchVm
{
    /// <summary>
    /// 批量更改对外发布状态
    /// </summary>
    /// <param name="isExternalPublish">是否对外发布</param>
    /// <returns>更新的数据数量</returns>
    public async Task<Result<int>> UpdateExternalPublishStatusAsync(bool isExternalPublish)
    {
        if (Ids == null || !Ids.Any())
        {
            return new Result<int>("请选择需要更改对外发布状态的招聘发布申请");
        }

        var entities = DC.Set<SysHrRecruitPublishRequestBill>()
            .Where(x => Ids.Contains(x.ID.ToString()))
            .ToList();

        if (!entities.Any())
        {
            return new Result<int>("未找到指定的招聘发布申请数据");
        }

        foreach (var entity in entities)
        {
            // 判断审批状态是否为“已完成”
            if (entity.WorkflowStatus != WorkflowStatus.已完成)
            {
                return new Result<int>($"招聘发布申请 {entity.BillCode} 的未审批完成，无法更改对外发布状态");
            }

            entity.IsExternalPublish = isExternalPublish;
            entity.UpdateTime = DateTime.Now;
            entity.UpdateBy = LoginUserInfo?.ITCode;
        }

        await DC.SaveChangesAsync();
        return new Result<int>(entities.Count);
    }


    /// <summary>
    /// 批量删除招聘发布申请
    /// </summary>
    /// <returns>删除的数据数量</returns>
    public async Task<bool> DoBatchDeleteAsync()
    {
        if (Ids == null || !Ids.Any())
        {
            MSD.AddModelError(" ", "请选择需要删除的招聘发布申请");
            return false;
        }

        var ids = Ids.Select(Guid.Parse).ToList();

        using var transaction = await DC.Database.BeginTransactionAsync();
        try
        {
            // 检查要删除的数据是否存在
            var existCount = await DC.Set<SysHrRecruitPublishRequestBill>()
                .CountAsync(x => ids.Contains(x.ID));

            if (existCount == 0)
            {
                MSD.AddModelError(" ", "未找到指定的招聘发布申请数据");
                return false;
            }

            // 批量清空用人需求池的关联ID（无需加载到内存）
            var updatedPoolsCount = await DC.Set<SysHrStaffPool>()
                .Where(x => x.RecruitPublishRequestBillId.HasValue &&
                            ids.Contains(x.RecruitPublishRequestBillId.Value))
                .ExecuteUpdateAsync(s => s
                    .SetProperty(x => x.RecruitPublishRequestBillId, (Guid?)null)
                    .SetProperty(x => x.UpdateTime, DateTime.Now)
                    .SetProperty(x => x.UpdateBy, LoginUserInfo.ITCode));

            // 批量删除招聘发布申请
            var deletedCount = await DC.Set<SysHrRecruitPublishRequestBill>()
                .Where(x => ids.Contains(x.ID))
                .ExecuteDeleteAsync();

            await transaction.CommitAsync();

            return true;
        }
        catch (Exception e)
        {
            await transaction.RollbackAsync();
            var errorMessage = e.Message;
            if (e.InnerException != null)
            {
                errorMessage += " " + e.InnerException.Message;
            }

            if (errorMessage.Contains("DELETE 语句与") ||
                errorMessage.Contains("REFERENCE 约束") ||
                errorMessage.Contains("FK_") ||
                errorMessage.Contains("constraint") ||
                errorMessage.Contains("外键约束"))
            {
                MSD.AddModelError(" ", "删除失败，该记录存在关联数据，请先删除相关信息");
            }
            else
            {
                MSD.AddModelError(" ", "删除失败，请联系管理员");
            }

            return false;
        }
    }
}